package cn.justforchris.system.service.impl;




import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.justforchris.jwt.JwtUtil;
import cn.justforchris.jwt.Payload;
import cn.justforchris.system.domain.Employee;
import cn.justforchris.system.domain.Logininfo;
import cn.justforchris.system.domain.Role;
import cn.justforchris.system.mapper.EmployeeMapper;
import cn.justforchris.system.mapper.LogininfoMapper;
import cn.justforchris.system.query.EmployeeQuery;
import cn.justforchris.system.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
@CacheConfig(cacheNames = "Employee")
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private HttpServletRequest request;
    @Override
    @Transactional
    @CacheEvict(key = "'employeeTree'")
    public void insertEmployee(Employee employee) {
        /*将数据插入到数据库,获取自增id,因为在sql中有设置id回填进对象id字段,所以这里可以获取到自增的id*/
        employeeMapper.insertEmployee(employee);
        List<Long> roles = employee.getRoles();
        /*获取前端传过来的角色id集合*/
        if (roles.size() > 0) {
            /*遍历角色id集合,将角色id与员工id关联放入中间表中*/
            employeeMapper.addEmployeeRole(employee);
        }
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(employee.getUsername());
        logininfo.setType(0);
        logininfo.setPhone(employee.getPhone());
        logininfo.setEmail(employee.getEmail());
        logininfo.setSalt(employee.getSalt());
        String salt = RandomUtil.randomString(32);
        logininfo.setSalt(salt);
        String password = employee.getPassword();
        String afterMd5Pwd = SecureUtil.md5(password + salt);
        logininfo.setPassword(afterMd5Pwd);
        if (employee.getState().equals("1")){
            logininfo.setDisable(true);
        }else {
            logininfo.setDisable(false);
        }
        logininfoMapper.insertLogininfo(logininfo);
        employee.setLogininfoId(logininfo.getId());
        employeeMapper.updateEmployee(employee);

    }

    @Override
    @Transactional
    @CacheEvict(key = "'employeeTree'")
    public void updateEmployee(Employee employee) {
        /*修改中间表数据的逻辑就是先删再增就行了*/
        employeeMapper.deleteEmployeeRole(employee.getId());
        List<Long> roles = employee.getRoles();
        /*获取前端传过来的角色id集合*/
        if (roles.size() > 0) {
            /*遍历角色id集合,将角色id与员工id关联放入中间表中*/
            employeeMapper.addEmployeeRole(employee);
        }
        employeeMapper.updateEmployee(employee);
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(employee.getUsername());
        logininfo.setType(0);
        logininfo.setPhone(employee.getPhone());
        logininfo.setEmail(employee.getEmail());
        String salt = RandomUtil.randomString(32);
        logininfo.setSalt(salt);
        String password = employee.getPassword();
        String afterMd5Pwd = SecureUtil.md5(password + salt);
        logininfo.setPassword(afterMd5Pwd);
        logininfo.setId(employee.getLogininfoId());
        logininfoMapper.updateLogininfo(logininfo);
    }

    @Override
    @Transactional
    @CacheEvict(key = "'employeeTree'")
    public void deleteEmployee(Long id) {
        /*这里要注意删除顺序,先将关联数据删除,再去删除所在表的数据*/
        employeeMapper.deleteEmployeeRole(id);
        Employee employeeById = employeeMapper.getEmployeeById(id);
        logininfoMapper.deleteLogininfo(employeeById.getLogininfoId());
        employeeMapper.deleteEmployee(id);


    }

    @Override
    @Transactional
    @CacheEvict(key = "'employeeTree'")
    public void patchDelete(Long[] ids) {
        for (Long id : ids) {
            deleteEmployee(id);
        }

    }

    @Override
    public Employee getEmployeeById(Long id) {
        return employeeMapper.getEmployeeById(id);
    }

    @Override
    public List<Employee> getAll() {
        return employeeMapper.getAll();
    }

    @Override
    public PageInfo<Employee> queryPage(EmployeeQuery queryPage) {
        PageHelper.startPage(queryPage.getCurrentPage(),queryPage.getPageSize());
        List<Employee> data = employeeMapper.queryPage(queryPage);
        /*
        这里获取到的是符合传入参数currentpage和pagesize的数据,也就是说,如果不传pagesize就只有五条因为怕个size如果不传入的话就是5
        但是如果有pagesize传入就根据传入数据来
        */
        for (Employee employee : data) {
            List<Role> roleByEmployeeId = employeeMapper.findRoleByEmployeeId(employee.getId());
            employee.setDbroles(roleByEmployeeId);
        }

        return new PageInfo<>(data);
        /*这里面就包含了pagehelper帮忙计算出来的total(总共多少条,和根据分页提取出的数据)*/
    }

    @Override
    public void change(Employee employee) {
        String token = request.getHeader("Token");
        Payload payload = JwtUtil.parseJwtToken(token);
        Long id = payload.getLogininfo().getId();
        Long byLogininfoId = employeeMapper.findByLogininfoId(id);
        Employee employeeById = employeeMapper.getEmployeeById(byLogininfoId);
        String password = employee.getPassword();
        String salt = employeeById.getSalt();
        String s = SecureUtil.md5(password + salt);
        employeeById.setPassword(s);
        employeeMapper.updateEmployee(employeeById);
    }


}
